package com.jams.goodox.activity.serve.enterprise;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.adapter.PictureGroupAdapter;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.resp.CooperationResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.UserUtils;
import com.jams.goodox.utils.ViewUtils;
import com.jams.goodox.widget.BlankClickGridView;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import retrofit2.Call;

import static com.jams.goodox.activity.serve.enterprise.EnterpriseCooperationDetailActivity.COOPERATION;


/**
 * 企业合作
 */
public class EnterpriseCooperationActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.empty_view)
    LoadView emptyView;
    @Bind(R.id.refresh_cooperation)
    RefreshRecyclerView rcvInnings;
    @Bind(R.id.srl_cooperation)
    SwipeRefreshLayout srl;

    private List<Neighborhood> dataList;
    private int curPage;
    //private int clickItemPosition = -1;//用来记录点击的标记，详情页删除回调局部刷新

    private final int REQUEST_CODE = 1991;
    public static final int RESULT_CODE = 2017;
    public static final String FROM_HOME_PAGE_KEY = "FROM_HOME_PAGE_KEY";
    public static final int FROM_HOME_PAGE_VALUE = 1234;
    /**
     * 判断入口,从首页还是企业服务进入
     */
    private int mEntrance;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_enterprise_cooperation;
    }

    @Override
    protected void init() {
        mEntrance = getIntent().getIntExtra(FROM_HOME_PAGE_KEY, -1);
        if (mEntrance == FROM_HOME_PAGE_VALUE) { //从首页进入,发帖按钮隐藏
            StyleUtil.titleBackKey(this, "企业合作");
        } else {
            StyleUtil.titleBackKeyWithRightIconListener(this, "企业合作", R.mipmap.title_bar_add, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //拥有企业授权,才允许访问
                    if (UserUtils.checkIsCompetent()) {
                        Intent i = new Intent(mContext, EnterpriseCooperationPublishActivity.class);
                        startActivityForResult(i, REQUEST_CODE);
                    }
                }
            });
        }
        srl.setOnRefreshListener(this);
        dataList = new ArrayList<>();
        rcvInnings.setLayoutManager(new RefreshLinearLayoutManager(this));
        rcvInnings.setHasFixedSize(true);
        rcvInnings.setAdapter(new RecycleCommonAdapter<Neighborhood>(this, dataList, R.layout.item_enterprise_cooperation) {
            @Override
            public void convert(RecycleCommonViewHolder helper, Neighborhood item, int position) {
                setData(helper, item, position);

            }
        });
        rcvInnings.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                // 开启线加载更多数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getCooperationData();
                    }
                });

            }
        });
        rcvInnings.addItemDecoration(new RecyclerDivider(mContext, LinearLayoutManager.VERTICAL, 1, ContextCompat.getColor(this, R.color.shallow_divider)));

        onRefresh();
    }


    //获取企业合作列表
    private void getCooperationData() {
        Map<String,String> params = new HashMap<>();
        params.put("communityId",SePref.getCommunityId());
        params.put("curPage",curPage+"");
        params.put("pageSize", AppConfig.PagSize+"");
        if(mEntrance != FROM_HOME_PAGE_VALUE){
            params.put("userId", DataCacheManager.getInstance().getUser().getEnterpriseAdminId());//企业服务进入,只能看本企业的内容
        }
        enqueue(createCallService(EnterpriseService.class).enterpriseCooperation(params), new 
                RetrofitCallbackListener<CooperationResp>() {
            @Override
            public void onSuccess(Call<CooperationResp> call, CooperationResp result) {
                try {
                    rcvInnings.loadMoreComplete();
                    srl.setRefreshing(false);
                    if (result.data != null) {
                        if (curPage == 1) {
                            dataList.clear();
                        }
                        if (result.data.pageInfo == null) {
                            rcvInnings.setCanLoadMore(false);
                        } else {
                            rcvInnings.setCanLoadMore(result.data.pageInfo.isHasMore());
                        }
                        dataList.addAll(result.data.resultList);
                        curPage++;
                        rcvInnings.notifyData();
                    }
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common, R.string.no_cooperation_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                try {
                    rcvInnings.loadMoreComplete();
                    srl.setRefreshing(false);
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common, R.string.no_cooperation_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    //设置item数据
    private void setData(RecycleCommonViewHolder helper, final Neighborhood item, final int position) {
        try {
            helper.setSimpleDraweeView(R.id.sdv_innings_portrait_item, StringUtils.newString(item.getUserSimple().getPortraitUrl())).setText(R.id.tv_innings_name_item, item.getUserSimple().getUserName()).setText(R.id.tv_innings_type_item, item.getLabel()).setText(R.id.tv_innings_content, item.getTopicContent()).setText(R.id.tv_innings_list_publish_time, item.getIntime()).setText(R.id.tv_good_item, item.getTopicPraise() + "").setText(R.id.tv_comment_item, item.getTopicMsgcnt() + "");
            //修改标签宽度
            ViewUtils.setLabelWidth(mContext, (TextView) helper.getView(R.id.tv_innings_type_item));
            setImageList((BlankClickGridView) helper.getView(R.id.gv_innings_item), item, position);
            helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                @Override
                public void itemClick() {
                    gotoDetailPage(item, position);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    srl.setRefreshing(true);
                    curPage = 1;
                    getCooperationData();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    /**
     * 设置图片
     */
    private void setImageList(BlankClickGridView gridView, final Neighborhood item, final int mPosition) {
        gridView.setVisibility(View.VISIBLE);
        PictureGroupAdapter gridAdapter = new PictureGroupAdapter(getContext(), item.getAnnexs(), 83, 3);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gotoDetailPage(item, mPosition);
            }
        });
        gridView.setOnTouchBlankPositionListener(new BlankClickGridView.OnTouchBlankPositionListener() {
            @Override
            public void onTouchBlank(MotionEvent event) {
                gotoDetailPage(item, mPosition);
            }
        });

    }


    //跳转到详情页
    private void gotoDetailPage(Neighborhood item, int position) {
        //clickItemPosition = position;
        Intent intent = new Intent(this, EnterpriseCooperationDetailActivity.class);
        intent.putExtra(COOPERATION, StringUtils.newString(item.getId()));
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode) {
            switch (resultCode) {
                case RESULT_CODE:
                    onRefresh();
                    break;
                default:
                    break;
            }
        }
    }

}
